import {
	defineStore
} from "pinia";

import {
	ref
} from "vue";

import {
	getUserInfoAPI,
	getUserStatsAPI,
} from '../apis/userAPI.js'


export const useUserStore = defineStore('user', () => {
	const token = ref('')
	const currentUser = ref({
		userId: '',
		username: '',
		phone: '',
		gender: '',
		avatarUrl: '',
		coverUrl: '',
		bio: '',
		level: '',
		points: '',
		location: '',
		birthday: '',
	})

	// 设置当前用户基础信息
	const setCurrentBaseUserInfo = (userData) => {
		token.value = userData.token
		currentUser.value.userId = userData.userId

		// 将基础信息存储到本地
		uni.setStorageSync('token', token.value);
		uni.setStorageSync('baseUserInfo', JSON.stringify({
			userId: userData.userId
		}));
	};

	// 获取当前用户完整信息
	const fetchCurrentFullUserInfo = async () => {
		try {
			// 获取用户基本信息
			const userRes = await getUserInfoAPI(currentUser.value.userId)
			// 获取用户统计信息（粉丝人数，关注人数和互关人数）
			const statsRes = await getUserStatsAPI(currentUser.value.userId)


			// 存储信息
			if (userRes.data.code === 20000 && statsRes.data.code === 20000) {
				let userData = userRes.data.data;

				currentUser.value = {
					...currentUser.value,
					username: userData.username,
					phone: userData.phone,
					gender: userData.gender,
					avatarUrl: userData.avatarUrl,
					coverUrl: userData.coverUrl,
					bio: userData.bio,
					level: userData.userLevel,
					points: userData.userPoints,
					lastUsernameUpdateTime: userData.lastUsernameUpdateTime,
					location: userData.location,
					birthday: userData.birthday,
					stats: statsRes.data.data
				}

				// console.log('用户完整信息', currentUser.value);

				// 将完整用户信息存储到本地
				uni.setStorageSync('fullUserInfo', JSON.stringify(currentUser.value))
			}

		} catch (error) {
			console.error('获取用户信息失败:', error)
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			})
		}
	}

	// 清除用户数据（退出账号）
	const clearUserData = () => {
		token.value = '';
		currentUser.value = {
			userId: '',
			username: '',
			phone: '',
			gender: '',
			avatarUrl: '',
			coverUrl: '',
			bio: '',
			level: '',
			points: '',
			location: '',
			birthday: '',
		};

		uni.clearStorageSync(); // 清除所有存储
		// 重置Pinia持久化插件的状态
		this.$reset();
	};

	// 初始化加载数据
	const init = () => {
		try {
			const saveBaseInfo = uni.getStorageSync('baseUserInfo');
			const saveFullInfo = uni.getStorageSync('fullUserInfo');

			if (saveBaseInfo) {
				currentUser.value.userId = JSON.parse(saveBaseInfo).userId;
			}
			if (saveFullInfo) {
				currentUser.value = JSON.parse(saveFullInfo);
			}
			token.value = uni.getStorageSync('token');
		} catch (error) {
			console.error('初始化用户数据失败:', error);
			// 异常时自动清除数据
			clearUserData();
		}
	}

	return {
		token,
		currentUser,
		setCurrentBaseUserInfo,
		fetchCurrentFullUserInfo,
		clearUserData,
		init
	}

}, {
	persist: true
});